package com.ncmmall.mall.controller.business.withdraw;

import com.ncmmall.application.business.withdraw.MerchantWithdrawApplication;
import com.ncmmall.domain.business.setting.SystemSetting;
import com.ncmmall.domain.business.trading.MerchantWithdrawApply;
import com.ncmmall.domain.business.trading.TradingLog;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 交易流水
 *
 * @author likaikai
 * @date 2019-07-22 15:38:57
 */
@Controller
@RequestMapping("/merchant/trading")
public class MerchantTradingController {

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private MerchantWithdrawApplication merchantWithdrawApplication;

    private final Logger logger = LoggerFactory.getLogger(MerchantTradingController.class);

    /**
     * 交易流水列表
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model, PageParams pageParams, TradingLog params) throws ParseException {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo()).setPageSize(20);

        Map<String, Object> map = new HashMap<>();
        map.put("id", Securitys.currentUser().getId());

        String sql = buildSql("select t from TradingLog t where t.merchant.id = :id ", map, params);

        QueryPage<TradingLog> page = queryChannelService.findPage(sql, pageRequest.setParams(map), TradingLog.class);

        double totalAmount = queryChannelService.selectSum("select ifnull(sum(o.amount),0) from mall_trading_log o where o.merchant_id = :id and type in (1,4,5) ", ImmutableMap.of("id", Securitys.currentUser().getId()));
        double noAmount = queryChannelService.findOne(QWebUser.webUser.eq(Securitys.currentUser()), WebUser.class).getBalance();
        double applyAmount = queryChannelService.selectSum("select ifnull(sum(o.amount),0) from mall_merchant_withdraw_apply o where o.status in(1,2,4) and o.merchant_id = :id ", ImmutableMap.of("id", Securitys.currentUser().getId()));
        double amount = queryChannelService.selectSum("select ifnull(sum(o.amount),0) from mall_merchant_withdraw_apply o where o.status = 5 and o.merchant_id = :id ", ImmutableMap.of("id", Securitys.currentUser().getId()));

        model.addAttribute("params", params);
        model.addAttribute("page", page);
        model.addAttribute("totalAmount", totalAmount);
        model.addAttribute("noAmount", noAmount);
        model.addAttribute("applyAmount", applyAmount);
        model.addAttribute("amount", amount);

        return "merchant/trading/list";
    }

    /**
     * 申请提现
     */
    @RequestMapping(value = "/applyWithdraw", method = RequestMethod.GET)
    private String applyWithdraw(Model model) {

        SystemSetting setting = queryChannelService.queryOneEntity("select * from mall_system_setting limit 1", Collections.emptyMap(), SystemSetting.class);

        model.addAttribute("_method", "PUT")
                .addAttribute("withdraw", new MerchantWithdrawApply())
                .addAttribute("setting", setting)
                .addAttribute("merchant", queryChannelService.findOne(QWebUser.webUser.id.eq(Securitys.currentUser().getId()), WebUser.class));

        return "merchant/trading/applyWithdraw";
    }

    /**
     * 申请提现
     */
    @RequestMapping(value = "/applyWithdraw", method = RequestMethod.PUT)
    @ResponseBody
    private Map<String, Object> applyWithdraw(MerchantWithdrawApply withdrawApply) {
        try {

            WebUser merchant = queryChannelService.findOne(QWebUser.webUser.eq(Securitys.currentUser()), WebUser.class);
            if (withdrawApply.getAmount() > merchant.getBalance()) {
                return ImmutableMap.of("status", false, "message", "余额不足");
            }

            withdrawApply.setMerchant(Securitys.currentUser());
            merchantWithdrawApplication.applyWithdraw(withdrawApply);

            return ImmutableMap.of("status", true);

        } catch (IllegalArgumentException e) {
            return ImmutableMap.of("status", false, "message", e.getMessage());
        } catch (Exception e) {
            logger.error("[申请提现异常]", e);
            return ImmutableMap.of("status", false, "message", "");
        }
    }


    /**
     * 条件查询
     */
    private String buildSql(String sql, Map<String, Object> map, TradingLog params) throws ParseException {

        if (!Strings.isNullOrEmpty(params.getOrderNo())) {
            sql += " and t.orderNo = :no ";
            map.put("no", params.getOrderNo());
        }

        if (!Strings.isNullOrEmpty(params.getBeginTime())) {
            sql += " and t.createTime >= :btime ";
            map.put("btime", new Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(params.getBeginTime() + " 00:00:00").getTime()));
        }

        if (!Strings.isNullOrEmpty(params.getEndTime())) {
            sql += " and t.createTime <= :etime ";
            map.put("etime", new Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(params.getEndTime() + " 23:59:59").getTime()));
        }

        sql += " order by t.createTime desc";

        return sql;
    }


}
